/**
 * SetupView implementation
**/

#include <unistd.h>
#import "iCountDown.h"
#import "CDList.h"
#import "SetupView.h"
#import "ToggleDisplayView.h"


@implementation myUIDatePicker : UIDatePicker
//this is called when the scroller stops rotating on a new value
- (void) pickerViewSelectionChanged:(id)datepicker
{
	//NSLog(@"myPicker: pickerViewSelectionChanged\n");
	[datepicker _updateDateOrTime];
	[_setupView setCounterValue: [datepicker date]];
}

//this is called to initialize the view of the picker
- (void) setPickerViewObject: (SetupView*)theView
{
	//NSLog(@"myPicker: setPickerViewObject\n");
	_setupView = theView;
}
@end

@implementation SetupView : UIView

- (id) initWithApplication: (iCountDown*)app withAppID: (NSString*)appID withFrame: (struct CGRect)rect withCDList: (CDList*)cdlist
{
	//get the main counter view
	_cdlist = cdlist;
	
	//make sure and use the application rect information
	_rect = rect;
	
	//indicate the size of navigation bar
	_navBarYSize = 42.0f;
	
	//Init view with frame rect
	[super initWithFrame: rect];
	
	//Save application object
	_application = app;
	_applicationID = appID;
	
	// setup transition view
	_transitionView = [[UITransitionView alloc] initWithFrame: _rect];
	
	_counter = [NSDate date];

	_table = [[UIPreferencesTable alloc] initWithFrame: CGRectMake(0.0f, _navBarYSize, rect.size.width, rect.size.height- _navBarYSize)];
	[_table setDelegate:self];
	[_table setDataSource:self];
	
	// Build Group
	_spacerGroup = [[UIPreferencesTableCell alloc] initWithFrame: CGRectMake(0.0f, _navBarYSize, rect.size.width, 24.0f)];
	[_spacerGroup setTitle: @""];
	_prefGroup = [[UIPreferencesTableCell alloc] initWithFrame: CGRectMake(0.0f, _navBarYSize, rect.size.width, 24.0f)];
	[_prefGroup setTitle: @""];

	// initialize the view for selecting a Display type for the count down timer
	_toggleDisplayView = [[ToggleDisplayView alloc] initWithFrame: CGRectMake(0.0f, 1.0f, rect.size.width, rect.size.height) 
		withApp: app 
		withCDList: cdlist
		withSetupView: self];
	[_toggleDisplayView setDelegate: self];

	_timePicker = [[myUIDatePicker alloc] initWithFrame:CGRectMake(0.0f, _navBarYSize+208.0f, _rect.size.width, _rect.size.height)];
	// 0 time hours/minutes plus am/pm small
	// 1 date month/day/year
	// 2 month/day/hour/minutes/am-pm
	// 3 time 24 hours/minutes large
	// 4&7 crashes app
	[_timePicker setDatePickerMode: 0];
	[_timePicker setDate: _counter];
	[_timePicker setPickerViewObject: self];
	[_timePicker setDelegate: self];
	double interval = 100.0f*(60*60*24.0f)*365.0f;
	[_timePicker setMaxDate : [NSDate dateWithTimeIntervalSinceNow: interval]];
	interval *= -1.0f;
	[_timePicker setMinDate : [NSDate dateWithTimeIntervalSinceNow: interval]];

	//NSLog(@"Setup View: initWithApplication\n");
	
	_timePickerShown = FALSE;

	return self;
	
}

/**
 * Diplays a date selector Picker
**/
- (void) makeDateSelectorActive
{	
	_timePickerShown = FALSE;
	[_timePicker setDatePickerMode: 1]; // set the type of picker to Month:Day:Year
	[self addSubview: _timePicker];
}

/**
* Displays a time selector Picker
*/
- (void) makeTimeSelectorActive
{
	_timePickerShown = TRUE;
	[_timePicker setDatePickerMode: 0]; // set the type of picker to HH:MM:A/P
	[self addSubview: _timePicker];	
}

/**
* Loads a display selector screen
*/
- (void) makeDisplaySelectorActive
{
	[_table removeFromSuperview];
	[_navbar removeFromSuperview];
		
	[_toggleDisplayView buildPreferencesTable];
	
	[self addSubview: _toggleDisplayView];
	
}

//this is called by UIDatePickers to change the counter
- (void) setCounterValue: (NSDate *)aCounter
{
	//NSLog(@"Setup View: setCounterValue\n");
	_counter = aCounter;
	
	if(_timePickerShown == TRUE)
	{
		UIPreferencesTableCell* cell = [[UIPreferencesTableCell alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, _navBarYSize)];
		[cell setTitle:@"Time:"];
		[cell setShowDisclosure:NO];
		[cell setValue: [_counter descriptionWithCalendarFormat:@"%H:%M:%S" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]];
		[_tableCells replaceObjectAtIndex:_nameCellIndex+2 withObject: cell];
		[cell release];
	}
	else
	{
		UIPreferencesTableCell* cell = [[UIPreferencesTableCell alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, _navBarYSize)];
		[cell setTitle:@"Date:"];
		[cell setValue: [_counter descriptionWithCalendarFormat:@"%m-%d-%Y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]];
		[cell setShowDisclosure:NO];
		[_tableCells replaceObjectAtIndex:_nameCellIndex+1 withObject: cell];
		[cell release];
	}
	[_table reloadData];

}

//this is called by CDList to setup and display this view
- (void) makeSetupActive: (NSDate *)aCounter
{
	//NSLog(@"Setup View: makeSetupActive with counter a\n");
	_counter = aCounter;
	//indicate nothing is selected currently
	_theSelectedPreference = -1;
	[_timePicker setDate: _counter];	
	[self buildPreferencesTable];
}

//upon exiting the Display type view this is called to get back to the preferences table
- (void) makeSetupActive
{
	[_toggleDisplayView removeFromSuperview];
	[_navbar removeFromSuperview];
	[self buildPreferencesTable];
}

/**
 * This builds of up the section list table, headers and all, with test data
**/
- (void) buildPreferencesTable
{
	//NSLog(@"Setup View: buildPreferences i\n");
	
	// setup nav bar
	[_navbar release];
	_navbar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, _navBarYSize)];
	UINavigationItem* title = [[UINavigationItem alloc] initWithTitle:@"Initialize CD"];
	[_navbar pushNavigationItem:title];
	[_navbar setBarStyle: 0];
	[_navbar enableAnimation];
	
	//Setup BACK button
	UINavBarButton* _backButton = [[UINavBarButton alloc] initWithFrame: CGRectMake(3.0f, 5.0f, 65.0f, 39.0f)];
	[_backButton setAutosizesToFit: FALSE];
	[_backButton setTitle: @"  BACK"];
	[_backButton addTarget: self action: @selector(makeCDListActive) forEvents: 1];
	[_backButton setNavBarButtonStyle: 2];
	[_navbar addSubview: _backButton];

	[_tableCells release];
	_tableCells = [[NSMutableArray alloc] init];
	int index = 0;

	UIPreferencesTextTableCell* cellt = [[UIPreferencesTextTableCell alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, 22.0f)];
	[cellt setTitle:@"Name:"];
	[cellt setValue:[_cdlist getSelectedCounterName]];
	[cellt setShowSelection:YES];
//	[[cellt textField] setAutoCapsType: 0];
//	[[cellt textField] setPreferredKeyboardType: 3];//2 is phone pad, 1 is numbers only, 0 has no space bar and numbers, 3 has no space bar
//	[[cellt textField] setAutoCorrectionType: 1];
//	[[cellt textField] showPreferredLayout]; //<- this method is not recognized and will crash the app
	[_tableCells addObject: cellt];
	//save the index for the Name cell
	_nameCellIndex = index;
	[cellt release];
	index++;
		
	UIPreferencesTableCell* cell = [[UIPreferencesTableCell alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, 22.0f)];
	[cell setTitle:@"Date:"];
	[cell setValue: [_counter descriptionWithCalendarFormat:@"%m-%d-%Y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]];
	[cell setShowDisclosure:NO];
	[_tableCells addObject: cell];
	[cell release];
	index++;
	
	cell = [[UIPreferencesTableCell alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, 22.0f)];
	[cell setTitle:@"Time:"];
	[cell setShowDisclosure:NO];
	[cell setValue: [_counter descriptionWithCalendarFormat:@"%H:%M:%S" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]];
	[_tableCells addObject: cell];
	[cell release];
	index++;
	
	cell = [[UIPreferencesTableCell alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, 22.0f)];
	[cell setTitle:@"Display Type:"];
	[cell setShowDisclosure:YES];
	switch ([_cdlist getSelectedCounterDisplayType])
	{
		case 0: 
			[cell setValue:[[NSString alloc] initWithFormat:@"Days:H:M:S"]]; 
			break;
		case 1: 
			[cell setValue:[[NSString alloc] initWithFormat:@"Seconds Only"]]; 
			break;
		case 2: 
			[cell setValue:[[NSString alloc] initWithFormat:@"Moons:D:H:M:S"]]; 
			break;
	}
	[_tableCells addObject: cell];
	[cell release];
	index++;
	
	cell = [[UIPreferencesTableCell alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, 18.0f)];
	[cell setTitle:@"Version"];
	[cell setValue:[_application getVersion]];
	[cell setShowSelection:NO];
	[_tableCells addObject: cell];
	[cell release];
	index++;
	
	//get the navBar on the screen
	[self addSubview: _navbar];
	
	//Refresh the fileview table
	[self addSubview: _table];
	[_table reloadData];
}

- (void) makeCDListActive
{
	//NSLog(@"Setup View: makeCDListActive a\n");
	[_timePicker removeFromSuperview];
	[_navbar removeFromSuperview];
	[_table removeFromSuperview];
	
	[_cdlist setEditedCounter: _counter];
	[_cdlist setSelectedCounterName: [[_tableCells objectAtIndex: _nameCellIndex] value]];
	[_cdlist redisplayCountDowns];
}

/**
 * Delegate Methods
**/
- (int)numberOfGroupsInPreferencesTable:(UIPreferencesTable*)aTable
{
	return 3;
}

- (int)preferencesTable:(UIPreferencesTable*)aTable numberOfRowsInGroup:(int)group
{
	switch( group )
	{
		case 0: return 1;
		case 1: return 1;
		case 2: return [_tableCells count];
		default: return 0;
	}
}

- (UIPreferencesTableCell*)preferencesTable:(UIPreferencesTable*)aTable cellForGroup:(int)group
{
	switch ( group )
	{
		case 0: return _spacerGroup;
		case 1: return _prefGroup;
		case 2: return _prefGroup;
		default: return Nil;
	}
}

- (float)preferencesTable:(UIPreferencesTable*)aTable heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed
{
	float groupLabelSize = 5.0f;
	switch( group )
	{
		case 0: return groupLabelSize;
		case 1: return groupLabelSize;
		default: return proposed;
	}
}

- (BOOL)preferencesTable:(UIPreferencesTable*)aTable isLabelGroup:(int)group
{
	switch ( group )
	{
		case 0: return FALSE;
		case 1: return FALSE;
		default: return FALSE;
	}
}

- (UIPreferencesTableCell*)preferencesTable:(UIPreferencesTable*)aTable cellForRow:(int)row inGroup:(int)group
{
	switch( group )
	{
		case 0: return _spacerGroup;
		case 1: return _prefGroup;
		case 2: return [_tableCells objectAtIndex:row];
	}
}

- (void)removeDisplayedItem
{
	//NSLog(@"Setup View: removeDisplayedItem\n");
	switch(_theSelectedPreference)
	{
	case 5: // Counter name
		//NSLog(@"Setup View: removeDisplayedItem %@\n",[[_tableCells objectAtIndex: _nameCellIndex] value]);
		[_cdlist setSelectedCounterName: [[_tableCells objectAtIndex: _nameCellIndex] value]];
		//disable the keyboard display for the counter name
		[_table setKeyboardVisible: FALSE];
		break;
	case 6: // date picker
		[_timePicker removeFromSuperview];
		break;
	case 7: // time picker
		[_timePicker removeFromSuperview];
		break;
	case 8: // Display type
		break;
	}
	[_table reloadData];
}

- (void) tableRowSelected: (NSNotification*) notification 
{
	[self removeDisplayedItem];
	//NSLog(@"Setup View: tableRowSelected\n");
	switch( [_table selectedRow] )
	{
		//Moving to Name entry - on screen keyboard display
		case 5:
			[_table setKeyboardVisible: TRUE];
//			[[_table keyboard] showPreferredLayout];
			break;
		//Moving to the date selection screen
		case 6: 
			[self makeDateSelectorActive]; 
			break;
		//Moving to the time selection screen
		case 7: 
			[self makeTimeSelectorActive]; 
			break;
		//Moving to type of counter display screen
		case 8: 
			[self makeDisplaySelectorActive]; 
			break;
	}
	_theSelectedPreference = [_table selectedRow];
	
}

- (void) setDelegate: (id)delegate;
{
	//NSLog(@"Setup View: setDelegate\n");

	_delegate = delegate;	
}

@end
	
